/**
 * Copyright(C) 2019 Hangzhou huhongchang Technology Co., Ltd. All rights reserved.
 */
package org.ericquan8.trojanserver.test.desktop1;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.ZipInputStream;

public class Server {
    public static int post = 10099;

    public static void main(String[] args) {


        try {
            ServerSocket ss = new ServerSocket(post);
            System.out.println("等待接客中");
            //界面
            JFrame jFrame = new JFrame("桌面监视");
            jFrame.setSize(1024, 768);
            jFrame.setLocationRelativeTo(null);
            jFrame.setLayout(new FlowLayout());

            jFrame.setAlwaysOnTop(true);
            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //读取分辨率
            double height = 0;
            double width = 0;


            JLabel backImage = new JLabel();
            JPanel panel = new JPanel();
            //滚动条
            JScrollPane jp = new JScrollPane(panel);
            panel.setLayout(new FlowLayout());
            panel.add(backImage);
            //设置窗口可见。
            jFrame.add(panel);
            jFrame.setVisible(true);
            while (true) {
                Socket client = ss.accept();
                //                System.out.println(String.format("客户端ip:%s:%s:", client.getInetAddress(), client.getPort()));
                DataInputStream dis = new DataInputStream(client.getInputStream());
                //使用多线程传输
                new ClientThread(dis, jFrame, backImage).start();
            }


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class ClientThread extends Thread {
    //数据输出流
    DataInputStream dataInput;
    JFrame jFrame;
    JLabel backImage;

    public ClientThread(DataInputStream dataInput, JFrame jFrame, JLabel backImage) {
        this.dataInput = dataInput;
        this.jFrame = jFrame;
        this.backImage = backImage;
    }

    @Override
    public void run() {
        //读取分辨率
        try {
            double height = dataInput.readDouble();
            double width = dataInput.readDouble();
            Dimension ds = new Dimension((int) width, (int) height);
            jFrame.setSize(ds);

            ZipInputStream zis = new ZipInputStream(dataInput);
            zis.getNextEntry();
            // 把ZIP流转换为图片
            backImage.setIcon(new ImageIcon(ImageIO.read(zis)));
            jFrame.repaint();
            //            zis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}